package com.wehealth;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.wehealth.adapter.Adapter_questionnaire_page2;
import com.wehealth.adapter.Adapter_questionnaire_page3;
import com.wehealth.adapter.Adapter_questionnaire_page4;
import com.wehealth.adapter.Adapter_questionnaire_page4_result;
import com.wehealth.dm.DM_Questionnaire_page2_item;
import com.wehealth.dm.DM_Questionnaire_page3_item;
import com.wehealth.dm.User;
import com.wehealth.util.DataManger;
import com.wehealth.util.QuestionnaireDataManager;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


@SuppressLint("ValidFragment")
public class Questionnaire_page4 extends Fragment {

	private MainActivity context;
	private static  String JSONResult;
	private QuestionnaireDataManager  mQuestionnaireDataManage;
	private  List<String>  mResultListStrs;
	private DataManger  mDataManger;

	public  Questionnaire_page4()
	{
		Log.i("init:", "Message"); 

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.questionnaire_page4, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		super.onActivityCreated(savedInstanceState);
		
		context =(MainActivity)getActivity();
		mResultListStrs = new ArrayList<String>();
		mDataManger = context.getDataManger();

		mQuestionnaireDataManage = QuestionnaireDataManager.getInstance();	
		List<String>  mResultPage3 = mQuestionnaireDataManage.getStringList();
		
		
        TextView reusltScore = (TextView)context.findViewById(R.id.questionnaire_page4_result_score);
        int score =mQuestionnaireDataManage.getScore();
        String scoreStr = String.valueOf(score);
        reusltScore.setText(scoreStr);

        float persent = (float) ((float)score/1000);
        
        ImageView  flag_icon = (ImageView)context.findViewById(R.id.questionnaire_page4_score_flag_icon);
        float  padding =  context.getResources().getDimension(R.dimen.questionnaire_page4_margin);
        int screenWidth = context.getWindowManager().getDefaultDisplay().getWidth(); 

        
        float   zoonwidth = screenWidth -padding*2;
        
        float  flag_icon_x = zoonwidth*persent;
        
        Log.d("SIMMON","  zoonwidth=  "+zoonwidth);
        Log.d("SIMMON","  flag_icon_x=  "+flag_icon_x);
        Log.d("SIMMON","  persent=  "+persent);
        flag_icon.setX(flag_icon_x);
        
        TextView  healthy_plan = (TextView)context.findViewById(R.id.questionnaire_page4_result_plan);
   
        String  reuslt1 = null;
        if(score >600 && score <= 800){
        	if(mQuestionnaireDataManage.getPlanId()==0){
        		mQuestionnaireDataManage.setPlanId(4);
        	}
        	//healthy_plan.setText(subhealthy_plan);
        	reuslt1 = getString(R.string.questionaire_page4_result2);
        }else if(score >800){
        	reuslt1 = getString(R.string.questionaire_page4_result3);
        }else if(score < 600){
        	reuslt1 = getString(R.string.questionaire_page4_result1);
        }
        
        String  subhealthy_plan = null;//getString(R.string.questionaire_page4_recommend_project1);
        switch (mQuestionnaireDataManage.getPlanId()) {
		case 1:
			subhealthy_plan = getString(R.string.questionaire_page4_recommend_project1);
			break;
		case 2:
			subhealthy_plan = getString(R.string.questionaire_page4_recommend_project2);
			break;
		case 3:
			subhealthy_plan = getString(R.string.questionaire_page4_recommend_project3);
			break;
		case 4:
			subhealthy_plan = getString(R.string.questionaire_page4_recommend_project4);
			break;
		case 5:
			subhealthy_plan = getString(R.string.questionaire_page4_recommend_project5);
			break;

		default:
			break;
		}
        healthy_plan.setText(subhealthy_plan);
        connectServierCreatePlanId();
        
        
        mResultListStrs.add(reuslt1);
        
        int  length = mResultPage3.size();
        if(length > 0){
	        for(int k = 0; k < length;k++){
	        	mResultListStrs.add(mResultPage3.get(k));
	        }
        }
        
        
        
        
        String[] planList = context.getResources().getStringArray(R.array.questionnaire_page4_plan_list);
        List<String> mPlanList =new ArrayList<String>();
        for(int i=0;i <planList.length;i++){
        	if(i != mQuestionnaireDataManage.getPlanId()-1){
        		mPlanList.add(planList[i]);
        	}
        }
        
        Adapter_questionnaire_page4 adapter = new Adapter_questionnaire_page4(context, mPlanList);
        
        ListView   mListView = (ListView)context.findViewById(R.id.questionnair_page4_list_plan);
        mListView.setAdapter(adapter);
        
        ListView  mListViewResult =(ListView)context.findViewById(R.id.questionnair_page4_list_result);
        
        Adapter_questionnaire_page4_result adapter2 = new Adapter_questionnaire_page4_result(context, mResultListStrs);
        mListViewResult.setAdapter(adapter2);
        
        Button bt =(Button)context.findViewById(R.id.questionnaire_page4_next_bt);
        bt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				context.updateMenuSide();   
                Home vHome = new Home();
                context.switchContent(vHome);  
			}
		});
        
        

	}

	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message paramMessage) {
			super.handleMessage(paramMessage);
			if(JSONResult!=null){
				switch (paramMessage.what) {
					case 0:
					CreatePlanId(JSONResult);
					break;
					case 1:
						UpdatePlanIdData(JSONResult);
					break;
				default:
					break;
				}
						JSONResult =null;
			}else{
			  //  activity.openMainActivityDialog(); 
			}
		}
	};
	
	
private void connectServierUpdatePlanId(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					UpdatePlanId();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what =1;
			handler.sendMessage(msg);
			}
		}.start();
	}
	
	private void  UpdatePlanId() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.User_UpdateMyPlan_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 String userId = String.valueOf(mDataManger.getUserID());
		 params.add(new BasicNameValuePair("userID",userId));
		 String mPlanId =String.valueOf(mQuestionnaireDataManage.getPlanId());
		 params.add(new BasicNameValuePair("planID",mPlanId));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","########  JSONResult="+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	
	
	
	private void connectServierCreatePlanId(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					Plan_CreateUserPlan();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what =0;
			handler.sendMessage(msg);
			}
		}.start();
	}
   

	private void  Plan_CreateUserPlan() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.Plan_CreateUserPlan_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 
		 String userId = String.valueOf(mDataManger.getUserID());
		 params.add(new BasicNameValuePair("userID",userId));
		 String mPlanId =String.valueOf(mQuestionnaireDataManage.getPlanId());
		 params.add(new BasicNameValuePair("recommendID",mPlanId));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","###!!!!!!!Plan_Day  JSONResult="+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	   private void CreatePlanId(String strJSON){
	       try{
	
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                String  result =   jsonObject.getString("result");
	               if(result.equals("1")){
	          		 	String mPlanId =String.valueOf(mQuestionnaireDataManage.getPlanId());
	            	    mDataManger.setRecommendID(mPlanId);
	             	   Log.d("SIMMON","###!!!!!!!Questionnaire  CreatePlanId");
	             	  connectServierUpdatePlanId();
	               }else{
	            	   context.openDialogBt(-100); 
	               }
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	
	   private void UpdatePlanIdData(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                String  result =   jsonObject.getString("result");
	               if(result.equals("1")){
	            	   Log.d("SIMMON","#########sucess");
	               }else{
	            	   context.openDialogBt(-100); 
	               }
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	
	
	

}
